import {boardColSize, boardRowSize, listToArray} from "@/utils/board-utils";

/**
 * 判断游戏是否胜利
 * @param gameMap
 * @param to
 * @returns {boolean} true: 结束
 * @constructor
 */
const CheckWin = (gameMap, to) => {
  // 棋盘数组二维化
  const board = listToArray(gameMap);
  // 计步变量和胜利要累计的个数变量
  let count = 1;
  const winCount = 5;
  // 结束坐标
  const {x, y, isBlackColor} = to;

  for (let i = x - 1; i >= 0; --i) {
    const chess = board[i][y];
    if (chess && chess.isBlackColor === isBlackColor) {
      count++;
    } else {
      break;
    }
  }

  for (let i = x + 1; i < boardRowSize; ++i) {
    const chess = board[i][y];
    if (chess && chess.isBlackColor === isBlackColor) {
      count++;
    } else {
      break;
    }
  }
  if (count >= winCount) {
    return true;
  } else {
    count = 1;
  }

  for (let i = y - 1; y >= 0; --i) {
    const chess = board[x][i];
    if (chess && chess.isBlackColor === isBlackColor) {
      count++;
    } else {
      break;
    }
  }
  for (let i = y + 1; y < boardColSize; ++i) {
    const chess = board[x][i];
    if (chess && chess.isBlackColor === isBlackColor) {
      count++;
    } else {
      break;
    }
  }

  if (count >= winCount) {
    return true;
  } else {
    count = 1;
  }

  for (let i = x + 1, j = y + 1; i < boardRowSize && j < boardColSize; ++i, ++j) {
    const chess = board[i][j];
    if (chess && chess.isBlackColor === isBlackColor) {
      count++;
    } else {
      break;
    }
  }
  // ����
  for (let i = x - 1, j = y - 1; i >= 0 && j >= 0; --i, --j) {
    const chess = board[i][j];
    if (chess && chess.isBlackColor === isBlackColor) {
      count++;
    } else {
      break;
    }
  }

  if (count >= winCount) {
    return true;
  } else {
    count = 1;
  }

  for (let i = x + 1, j = y - 1; i < boardRowSize && j >= 0; ++i, --j) {
    const chess = board[i][j];
    if (chess && chess.isBlackColor === isBlackColor) {
      count++;
    } else {
      break;
    }
  }
  for (let i = x - 1, j = y + 1; i >= 0 && j < boardColSize; --i, ++j) {
    const chess = board[i][j];
    if (chess && chess.isBlackColor === isBlackColor) {
      count++;
    } else {
      break;
    }
  }
  return count >= winCount;
};

export default CheckWin;
